package com.smart.smartdata;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.inuker.bluetooth.library.connect.response.BleNotifyResponse;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.smart.smartdata.ble.SPO2BleManager;
import com.smart.smartdata.ble.TemperatureBleManager;
import com.smart.smartdata.eventbus.EventBus;
import com.smart.smartdata.eventbus.EventNames;
import com.smart.smartdata.models.UpdateDataModel;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.Bind;
import butterknife.ButterKnife;
import kr.co.namee.permissiongen.PermissionGen;

public class MessageListActivity extends AppCompatActivity  implements EventBus.SubscriberChangeListener{

    private  ListAdapter adapter;


    @Bind(R.id.recycle_view)
    RecyclerView recycle_view;

    @Bind(R.id.tk_refresh)
    TwinklingRefreshLayout tk_refresh;

    @Bind(R.id.tv_setting)
    TextView tv_setting;

    @Bind(R.id.tv_add)
    TextView tv_add;

    public  static  final String Cache_Key = "cache_key";
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message_list);
        StatusBarUtil.setRootViewFitsSystemWindows(this, false);
        StatusBarUtil.setTranslucentStatus(this);//透明状态栏

        ButterKnife.bind(this);


        ArrayList<MessageData> messageDataList = new ArrayList<>();





        adapter = new ListAdapter(messageDataList);

        adapter.setOnItemClickListener((adapter1, view, position) -> {



            Intent intent = new Intent();
            intent.putExtra("messageData",messageDataList.get(position));
            intent.setClass(this, RecorderDetailActivity.class);

            startActivity(intent);
        });
        adapter.setOnItemChildClickListener((adapter1, view, position) -> {
            if(view.getId() == R.id.tv_delete){

                messageDataList.remove(position);
                adapter.notifyItemRemoved(position);

                Gson gson = new Gson();
                String json = gson.toJson(messageDataList);


                SpUtils.put(Cache_Key, json);
            }
        });

        RcvInitUtils.initVerticalRcv(this, tk_refresh,recycle_view, adapter,new RefreshListenerAdapter(){


            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);

                refreshLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Gson gson = new Gson();
                        messageDataList.clear();

                        String cacheStr = (String)SpUtils.get(Cache_Key,"");


                        if(cacheStr != null && !"".equals(cacheStr)){


                            ArrayList<MessageData> md = gson.fromJson(cacheStr, new TypeToken<List<MessageData>>() {
                            }.getType());

                            messageDataList.addAll(md);
                        }
                        adapter.notifyDataSetChanged();
                        tk_refresh.finishRefreshing();

                    }
                },400);


             }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                tk_refresh.finishLoadmore();
            }
        });


        tv_add.setOnClickListener(view -> {
            AddTestDialog addTestDialog = new AddTestDialog();
            addTestDialog.show(getSupportFragmentManager(),"");
        });

        tv_setting.setOnClickListener(view -> {
            Intent intent = new Intent();
            intent.setClass(this,SettingActivity.class);

            startActivity(intent);
        });

        PermissionGen.with(this)
                .addRequestCode(100)
                .permissions(
                        Manifest.permission.BLUETOOTH_ADMIN,
                        Manifest.permission.BLUETOOTH,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION
                )
                .request();

    }

    @Override
    public void onSubscriberDataChanged(Object notificationName, Object content) {
        if (EventNames.CONNECT_SUCCESS == notificationName) {
            if (content != null) {
                String type = (String) content;
                if ("spo2".equals(type)) {
                    SPO2BleManager.getInstance().openNotify(SPO2BleManager.getInstance().getBleDevice().getMac(), new BleNotifyResponse() {
                        @Override
                        public void onNotify(UUID service, UUID character, byte[] value) {
                            String result = ByteUtil.toHexString(value).replace(" ", "");
                            Log.e("应答命令：", result);
                            int spo2 = Integer.parseInt(result, 16);
                            Log.e("血氧饱和度：", spo2 + "");
                            if (spo2 > 90) {
                                UpdateDataModel updateDataModel = new UpdateDataModel();
                                updateDataModel.data = spo2+"";
                                updateDataModel.type=type;
                                EventBus.getInstance().notifiDataUpdate(EventNames.UPDATE_DATA, updateDataModel);
                            }
                        }

                        @Override
                        public void onResponse(int code) {

                        }
                    });
                } else if ("temperature".equals(type)) {
                    TemperatureBleManager.getInstance().openNotify(TemperatureBleManager.getInstance().getBleDevice().getMac(), new BleNotifyResponse() {
                        @Override
                        public void onNotify(UUID service, UUID character, byte[] value) {
                            String result = ByteUtil.toHexString(value).replace(" ", "");
                            Log.e("应答命令：", result);
                            result = result.substring(6, 8) + result.substring(4, 6) + result.substring(2, 4) + result.substring(0, 2);
                            Log.e("转换命令：", result);
                            String temperature = String.format("%.1f", Integer.parseInt(result, 16) / 10000.0);
                            Log.e("体温：", temperature);
                            UpdateDataModel updateDataModel = new UpdateDataModel();
                            updateDataModel.data = temperature+"";
                            updateDataModel.type=type;
                            EventBus.getInstance().notifiDataUpdate(EventNames.UPDATE_DATA, updateDataModel);

                        }

                        @Override
                        public void onResponse(int code) {

                        }
                    });
                }
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        tk_refresh.startRefresh();

        EventBus.getInstance().subscribe(EventNames.CONNECT_SUCCESS, this);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getInstance().unSubscribe(EventNames.CONNECT_SUCCESS, this);
    }
}
